/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 *  Copyright 2008 Global Sign In
 * 
 *  This code is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef _WEBAPI_H_
#define _WEBAPI_H_

#include <libxml/parser.h>
#include <string>
#include <map>
#include <ostream>

#include "Campaign.h"
#include "CampaignSQL.h"
#include "MessageDetails.h"
#include "Recipient.h"
#include "UsageLogger.h"

/// Parses XML sent to the Web API abd outputs the response.
class WebAPI
{
	public:
		WebAPI(CampaignSQL *pCampaignData, UsageLogger *pLogger,
			std::ostream &outputStream);
		virtual ~WebAPI();

		/// Parses the XML request held in a buffer.
		bool parse(const char *pBuffer, unsigned int bufferLen);

	protected:
		CampaignSQL *m_pCampaignData;
		UsageLogger *m_pLogger;
		std::ostream &m_outputStream;
		std::string m_callName;
		std::string m_errorMsg;
		int m_errorCode;

		void outputCampaign(const Campaign &campaign,
			const std::string &detailLevels);

		void outputRecipient(const Recipient &recipient);

		void outputSuccess(std::map<std::string, bool> &items);

		void loadHeaderAttributes(xmlNode *pNode,
			std::string &name, std::string &emailAddress);

		MessageDetails *loadCampaign(xmlNode *pCampaignNode, Campaign &campaign);

		MessageDetails *loadMessage(xmlNode *pCampaignNode);

		void loadRecipient(xmlNode *pCampaignNode, Recipient &recipient);

		bool createAction(xmlNode *pCreateNode,
			std::map<std::string, std::string> &newItems);

		bool getAction(xmlNode *pGetNode);

		bool setAction(xmlNode *pSetNode,
			std::map<std::string, bool> &modifiedItems);

		bool listAction(xmlNode *pListNode);

		bool deleteAction(xmlNode *pDeleteNode,
			std::map<std::string, bool> &deletedItems);

	private:
		// WebAPI objects cannot be copied
		WebAPI(const WebAPI &other);
		WebAPI &operator=(const WebAPI &other);

};

#endif // _WEBAPI_H_
